package com.heiTie.heiTie.controller;

import com.heiTie.heiTie.common.BaseResponse;
import com.heiTie.heiTie.entity.Course;
import com.heiTie.heiTie.service.CourseService;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.jni.Buffer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.List;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class CourseController {
    @Autowired
    CourseService courseService;

    @GetMapping("/getCourseList")
    public BaseResponse getAllData(){
        List<Course> courseList = courseService.list();
        return BaseResponse.ok(courseList);
    }

    @PostMapping("/insertCourse")
    public BaseResponse insertCourse(@RequestBody Course course){
        Long id = course.getId();
        if(id > 0){
            courseService.updateById(course);
            return BaseResponse.ok("修改成功");
        }else {
            courseService.save(course);
            return BaseResponse.ok("插入成功");
        }

    }
    @PostMapping("/uploadfile")
    public BaseResponse uploadfile(@RequestParam(value = "file") MultipartFile File) throws Exception {
        String uploadFileName = courseService.uploadLogo(File);
        return BaseResponse.ok(uploadFileName);
    }


    @GetMapping("/file/download")
    public void fileDownload(HttpServletResponse response, @RequestParam("filePath") String filePath) throws UnsupportedEncodingException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new Error("当前下载的文件不存在，请检查路径是否正确");
        }
        // 清空 response
        response.reset();
        response.setCharacterEncoding("UTF-8");

        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
        response.setContentType("application/octet-stream");

        // 将文件读到输入流中
        try (InputStream is = new BufferedInputStream(Files.newInputStream(file.toPath()))) {

            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());

            byte[] buffer = new byte[1024];
            int len;

            //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
            while((len = is.read(buffer)) > 0){
                outputStream.write(buffer, 0, len);
            }
            outputStream.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @DeleteMapping("/delCourse")
    public BaseResponse insertCourse(@RequestParam String id){
        courseService.removeById(id);
        return BaseResponse.ok("删除成功");
    }



}
